package pers.cz.redis;

import pers.cz.config.ExtentTestNGIReporterListener;
import pers.cz.queue.AutoRequestQueue;
import pers.cz.queue.RequestQueue;
import pers.cz.testNg.AutoExtentTestNGIReporterListener;
import pers.cz.testNg.AutoTestNg;
import pers.cz.testNg.TestNg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.TestNG;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @program: PostGirl-panent
 * @description: JobDealThread
 * @author: Cheng Zhi
 * @create: 2021-07-23 13:03
 **/
public class TestCaseDealThread implements Runnable{


    private Logger logger = LoggerFactory.getLogger(TestCaseDealThread.class);

    private Integer count = 0;

    private final Integer timeOut = 0; // 设置为0表示阻塞

    private Jedis resource;

    private volatile Boolean flag = false;

    public TestCaseDealThread(Jedis resource ) {
        this.resource = resource;
    }

    public synchronized void stopThread(){
        flag = true;
    }

    @Override
    public void run() {

        while(!flag) {
            delMessage();
        }
    }

    public void delMessage() {

        List<String> testListQueue = resource.brpop(timeOut,"RUNTESTCASEQUEUE");
        logger.debug(Thread.currentThread().getName() + " consumer message,message=" + testListQueue + ",count=" + count);

        if (testListQueue != null && testListQueue.size()>0) {

            String ids = testListQueue.get(1); // 获取到的是测试案例编号和测试地址。中间以&符号分割

            String[] message = ids.split("\\^");

            // 数组最后一位为标识符号 REGRESSION表示回归案例
            if (message[3].equals("REGRESSION")) {
                RequestQueue.addQueue(ids);
                List<String> testNameList = new ArrayList<>();
                TestNG testNG = new TestNG();
                Class[] classes = {TestNg.class};
                testNG.setTestClasses(classes);
                testNG.setDefaultSuiteName(ids.toString());
                testNG.setTestNames(testNameList);
                //testNG.setListenerClasses(Collections.singletonList(ExtentTestNGIReporterListener.class));
                testNG.addListener(new ExtentTestNGIReporterListener());
                testNG.run();
            }

            // 数组最后一位为标识符号 AUTO表示自动化案例
            if (message[3].equals("AUTO")) {
                AutoRequestQueue.addQueue(ids);
                List<String> testNameList = new ArrayList<>();
                TestNG testNG = new TestNG();
                Class[] classes = {AutoTestNg.class};
                testNG.setTestClasses(classes);
                testNG.setDefaultSuiteName(ids.toString());
                testNG.setTestNames(testNameList);
                testNG.setListenerClasses(Collections.singletonList(AutoExtentTestNGIReporterListener.class));
                testNG.run();
            }
        }
        count ++;
    }
}
